﻿using SelfMadeMillionaire.Core.DTOs;
using SelfMadeMillionaire.Core.Enums;
using SelfMadeMillionaire.Core.Repositories;
using SelfMadeMillionaire.Core.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SelfMadeMillionaire.BLL.Services
{
	public class PaymentService : IPaymentService
	{
		readonly IPayPalPaymentRepository _paypalPaymentRepository;
		readonly IPayPalBuyerRepository _paypalBuyerRepository;
		readonly IPayPalTransactionRepository _paypalTransactionRepository;
		readonly ISubscriberService _subscriberService;
		readonly IOrderRepository _orderRepository;

		public PaymentService(IPayPalPaymentRepository paypalPaymentRepository,
			IPayPalBuyerRepository paypalBuyerRepository,
			IPayPalTransactionRepository paypalTransactionRepository,
			ISubscriberService subscriberService,
			IOrderRepository orderRepository)
		{
			_paypalBuyerRepository = paypalBuyerRepository;
			_paypalPaymentRepository = paypalPaymentRepository;
			_paypalTransactionRepository = paypalTransactionRepository;
			_subscriberService = subscriberService;
			_orderRepository = orderRepository;
		}

		public void PayPalProcess(PayPalPaymentDto payment)
		{
			var order = _orderRepository.Get(Convert.ToInt32(payment.Payment.Custom));
			payment.Payment.Order = order;
			payment.Transaction.Payment = payment.Payment;
			payment.Transaction.Buyer = payment.Buyer;
			
			_paypalTransactionRepository.Add(payment.Transaction);


			order.Subscriber.ProductType = order.ProductType;
			order.Subscriber.SubscriptionLevel = order.SubscriptionLevel;
			//order.Subscriber.EndDate = order.ExperationDate;
            order.Subscriber.EndDate = DateTime.Today.Date.AddYears(1);
			order.Subscriber.SmmUnsubscribed = false;
			
			order.Status = (byte)StatusType.Paid;

			_orderRepository.Commit();
		}


		public double GetBalance(string subscriberEmail)
		{
			var order = _orderRepository.GetAll().FirstOrDefault(x => x.Subscriber.Email == subscriberEmail && x.Status == (byte)StatusType.Paid);//  _subscriberService..GetOrder(subscriberEmail);

			if (order == null)
				return 0;

			return _paypalPaymentRepository.GetAll().Where(x => x.Custom == order.ID.ToString()).Sum(x => x.McGross);
		}


		public IEnumerable<PayPalPaymentDto> GetPayments()
		{
			var transactions = _paypalTransactionRepository.GetAll().Select(x => new PayPalPaymentDto
			{
				Buyer = x.Buyer,
				Payment = x.Payment,
				Transaction = x
			});

			return transactions;
		}
	}
}
